package com.conversionservice;

import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 对{@link ConversionService} 的自定义实现
 * 能识别 {@link DateTimeFormat#pattern()} 中配置的日期格式
 * 并将字符串转为 {@link LocalDateTime} 对象
 */
public class DateTimeConversionService implements ConversionService {
    @Override
    public boolean canConvert(Class<?> sourceType, Class<?> targetType) {
        return true;
    }

    @Override
    public boolean canConvert(TypeDescriptor sourceType, TypeDescriptor targetType) {
        boolean targetIsLocalDateTime = targetType.getObjectType().isAssignableFrom(LocalDateTime.class);
        DateTimeFormat annotation = targetType.getAnnotation(DateTimeFormat.class);
        boolean isFromString = sourceType.getObjectType().isAssignableFrom(String.class);
        return isFromString && targetIsLocalDateTime && annotation != null && StringUtils.hasLength(annotation.pattern());
    }

    @Override
    public <T> T convert(Object source, Class<T> targetType) {
        return null;
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {

        DateTimeFormat annotation = targetType.getAnnotation(DateTimeFormat.class);

        return LocalDateTime.parse(source.toString(),DateTimeFormatter.ofPattern(annotation.pattern()));

    }
}
